package com.hz.ruoyimotor.hanlder;

import com.hz.rouyigonggong.domain.basedomain.BaseDomain;
import com.ruoyi.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class TenantInterceptor implements HandlerInterceptor {
//    @Autowired
//    private CustomTenantHandler customTenantHandler;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取 Authorization 请求头
        String authHeader = request.getHeader("Authorization");
//        System.out.println("Authorization: " + authHeader);
        if (authHeader != null && authHeader.startsWith("Bearer")) {
            String token = authHeader.substring("Bearer ".length());
            Claims claims = JwtUtils.parseToken(token);
            String userid = JwtUtils.getUserId(claims);
//            System.out.println("租户ID：" + userid);
            if (userid != null) {
                BaseDomain.setUserId(Integer.parseInt(userid));
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清理 ThreadLocal
        TenantContext.clear();
    }
}
